package com.surveypark.service.impl;

import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.surveypark.dao.BaseDao;
import com.surveypark.domain.User;
import com.surveypark.domain.security.Role;
import com.surveypark.service.RoleService;
import com.surveypark.service.UserService;
import com.surveypark.util.StringUtil;
import com.surveypark.util.ValidateUtil;

/**
 * UserServiceImpl
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements
		UserService {
	
	@Resource(name="roleService")
	private RoleService roleService;
	@Override
	@Resource(name="userDao")
	public void setDao(BaseDao<User> dao) {
		super.setDao(dao);
	}

	@Override
	public boolean isRegister(String email) {
		
		String hql = "from User u where u.email = ?";
		List<User> users = findEntityByHQL(hql, email); 
		return ValidateUtil.isValid(users);
	}

	@Override
	public User validateLogin(String email, String password) {
		
		String hql = "from User u where u.email=? and u.password=?";
		List<User> users = findEntityByHQL(hql, email, password);
		return ValidateUtil.isValid(users)?users.get(0):null;
	}

	@Override
	public User getUserWithRole(Integer userId) {
		User u = this.getEntity(userId);
		u.getRoles().size();
		return u;
	}

	@Override
	public void updateAuthorize(Integer userId, Integer[] ownRoleIds) {

		User uu = this.getEntity(userId);
		if(!ValidateUtil.isValid(ownRoleIds)){
			uu.getRoles().clear();
		}
		else{
			String hql = "from Role r where r.id in (" + StringUtil.arr2Str(ownRoleIds) + ")";
			List<Role> roles = roleService.findEntityByHQL(hql);
			uu.setRoles(new HashSet<Role>(roles));
		}
	}

	@Override
	public void clearAuthorize(Integer userId) {

		this.getUserWithRole(userId).getRoles().clear();
	}
	
}
